import Sker from '@/utils/sker'
import React, { useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import cm from 'classnames'

function Select(props) {
  const {
    list,
    width = 145,
    onChange,
    maxHeight = 200,
    className,
    placeholder = '请选择',
    currentValue,
    valueName = 'value',
    labelName = 'label',
    needPrefix
  } = props
  const [expend, setExpend] = useState(false)
  const [selected, setSetects] = useState(null)
  const widthRem = width / 16 + 'rem'
  const contentRef = useRef(null)
  const selectEventName = useRef(Symbol('select'))
  // 当前选中值
  const placeholders = useMemo(() => {
    if (selected) {
      return selected[labelName]
    } else {
      return placeholder
    }
  }, [selected])

  // 动态获取当前item高度
  const height = useMemo(() => {
    if (expend) {
      return contentRef.current?.offsetHeight ?? 0
    } else {
      return 0
    }
  }, [expend])

  const select = (e, item) => {
    e.stopPropagation()
    setExpend(false)
    onChange?.(item[valueName])
    setSetects(item)
  }

  // 展开收起select
  const selectClick = ev => {
    ev.stopPropagation()
    Sker.dispatch('select', { name: selectEventName.current })
    setExpend(!expend)
  }

  // 全局click点击，Select失焦
  useEffect(() => {
    const click = () => {
      setExpend(false)
    }
    const removeListen = Sker.listen('select', event => {
      if (event.detail.name !== selectEventName.current) {
        setExpend(false)
      }
    })
    window.addEventListener('click', click)
    window.addEventListener('blur', click)
    return () => {
      removeListen()
      window.removeEventListener('click', click)
      window.removeEventListener('blur', click)
    }
  }, [])

  // 动态插值
  useEffect(() => {
    if (currentValue) {
      const currVal = list.find(item => item[valueName] == currentValue)
      if (currVal) {
        setSetects(currVal)
      }
    }
  }, [currentValue])

  return (
    <div style={{ width: widthRem, ...props.style }} className={cm(styles['select-container'], className)}>
      <div className={styles['select-title']} onClick={selectClick}>
        <div className={cm(styles['select-title-text'], 'textEllipsis')}>
          {needPrefix && <span className="mr-5">选集播放</span>}
          {placeholders}
        </div>
        <img
          src="/images/arrow.webp"
          alt=""
          className={cm(styles['select-title-arrow'], expend ? styles.activeEnter : styles.activeLeave)}
        />
      </div>

      <div className={cm(styles['select-options'], !expend ? styles.unactive : styles['expend-options'])}>
        <div className={styles['select-items-box']} style={{ height: height, maxHeight: maxHeight }}>
          <ul ref={contentRef} className={cm(styles['select-items'])}>
            {list.map((item, index) => (
              <li
                key={index}
                onClick={e => select(e, item)}
                className={cm(styles['select-item'], { [styles.active]: item[valueName] === selected?.[valueName] })}
              >
                {item[labelName]}
              </li>
            ))}
          </ul>
        </div>
      </div>
    </div>
  )
}

export default React.memo(Select)
